package club.cearnach.api.websocket.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author 阮胜
 * @date 2018/4/12 13:40
 */
@Component
@Slf4j
@ServerEndpoint("/admin/socket/comment/{account}")
public class CommentSocketServer {
    public static final ConcurrentMap<String, Session> socketSessionMap = new ConcurrentHashMap<>();
    private Session session;
    private String account;

    @OnOpen
    public void onOpen(@PathParam("account") String account, Session session) {
        socketSessionMap.put(account, session);
        this.account = account;
        this.session = session;
        sendMsg(session, "连接成功 ! Account: " + account);
    }

    @OnMessage
    public void onMessage(@PathParam("account") String account, String msg) {

    }

    @OnClose
    public void onClose() {
        log.info("WebSocketServer: 用户 {} 已断开连接!", account);
        socketSessionMap.remove(this.account);
    }

    @OnError
    public void onError(Throwable throwable) {
        sendMsg(session, throwable.getMessage());
    }

    public static void sendMsg(Session session, String msg) {
        try {
            session.getBasicRemote().sendText(msg);
        } catch (Exception e) {
            log.error("CommentWebSocket 已经关闭 , 无法发送数据 {}", msg);
        }
    }
}
